# -*- coding: utf-8 -*-
# pywot - what's on tv today?
# Copyright (C) 2010 Ba1T <byte-f@live.it>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# -------------------------------------------------------------------------------

from gtk import *
from pygtk import *
from gobject import *
require ('2.0')
from web import *
from util import *
from pynotify import *
gdk.threads_init ()

class pwGUi:
	def update_treeview (self):
		self.liststore.clear ()
		ps = self.core.progs[self.to_show-1]
		#try:
		for p in ps:
			self.liststore.append ((p[0], p[1], p[2], p[3], p[4]))
		#except:
		#	pass
		
	#status bar
	def sts (self, msg):
		self.stat.push (0, " " + msg)
	
	#menus signals
	def menu_reload (self, w, data=None):
		w = WebThrd (self)
		w.start ()
	
	def senst (self):
		s = self.to_show
		if s == 7:
			self.btnAdd.set_sensitive (False)
			self.btnRemove.set_sensitive (True)
			#self.mnuDS.set_sensitive (True)
		else:
			self.btnAdd.set_sensitive (True)
			self.btnRemove.set_sensitive (False)
			#self.mnuDS.set_sensitive (False)
	def menu_show (self, w, n):
		self.to_show = int (n)#-1
		self.chann (None, None)
		self.senst ()
	
	def menu_notif (self, w, d=None):
		pass

	def menu_pref (self, w, d=None):
		pass

	def menu_about (self, w, d=None):
		self.dlgsh (None, None, True)
	
	def dlgsh (self, wid, wia, w=True):
		if w == True:
			self.winAbout.show ()
		else:
			self.winAbout.hide ()
	
	def is_in_arr (self, arr, d1=None, d2=None, d3=None):
		try:
			for p in arr:
				if p[1] == d1 and p[2] == d2 and p[3] == d3:
					return True
			return False
		except:
			return False
		
	def listDblClick (self, w, row, col, d=None):
		if self.to_show == 7:
			self.notf (self.btnRemove, "rem")
			return
		_id = int (self.liststore[row][0]) - 1
		_name = self.liststore[row][1]
		_when = self.liststore[row][2]
		_type = self.liststore[row][3]
		_chan = self.liststore[row][4]
		progzs = [_id, _name, _when, _type, _chan]
		h = self.is_in_arr (self.core.progz, _name, _when, _type)
		if h == False:
			self.sts ('%s aggiunto nella lista dei programmi da notificare.' % (_name))		
			self.core.progz.append (progzs)
		else:
			self.sts ('Programa già in lista per una notifica.')

	def show_config (self, w, d=None):
		self.sts ('TODO: Da implementare nelle prossime versioni, stay tuned ;)')
		#TODO
				
	def chann (self, w, d):
		if d == 'next':
			self.to_show += 1
		elif d == 'forw':
			self.to_show -= 1
		if self.to_show == 7:
			self.btnNext.set_sensitive (False)
		else:
			self.btnNext.set_sensitive (True)
		if self.to_show == 1:
			self.btnForw.set_sensitive (False)
		else:
			self.btnForw.set_sensitive (True)
		if self.to_show == 1:
			self.lblCh.set_markup ('Programmazione per: <b>Rai 1</b>')
		elif self.to_show == 2:
			self.lblCh.set_markup ('Programmazione per: <b>Rai 2</b>')
		elif self.to_show == 3:
			self.lblCh.set_markup ('Programmazione per: <b>Rai 3</b>')
		elif self.to_show == 4:
			self.lblCh.set_markup ('Programmazione per: <b>Rete 4</b>')
		elif self.to_show == 5:
			self.lblCh.set_markup ('Programmazione per: <b>Canale 5</b>')
		elif self.to_show == 6:
			self.lblCh.set_markup ('Programmazione per: <b>Italia 1</b>')
		elif self.to_show == 7:
			self.lblCh.set_markup ('Programmazione per: <b>I programmi da notificare</b>')
		self.update_treeview ()
		self.senst ()

	def delete_from_notf (self, _id, name, tp, tm):
		for p in self.core.progz:
			#print str (str (p[0]) + p[1] + p[2] + p[3])
			#print str (str (_id) + name + tp + tm)
			if str (p[0]) == str (_id) and p[1] == name and p[2] == tp and p[3] == tm:
				self.sts (name + ' rimosso dalla lista dei programmi da notificare (#' + str (_id) + ')')
				self.core.progz.remove (p)
				
	#add-remove button
	def notf (self, w, d=None):
		try:
			mod, i = self.treeview.get_selection ().get_selected ()
		except:
			i = None
		if i == None:
			self.sts ('Devi selezionare un programma prima di compiere un azione.')
			return None
		if d == 'add':
			_name = self.liststore.get_value (i, 1)
			_when = self.liststore.get_value (i, 2)
			_type = self.liststore.get_value (i, 3)
			chann = self.liststore.get_value (i, 4)
			progzs = [_name, _when, _type, chann]
			h = self.is_in_arr (self.core.progz, _name, _when, _type)
			if h == False:
				self.sts ('%s aggiunto nella lista dei programmi da notificare.' % (_name))		
				self.core.progz.append (progzs)
			else:
				self.sts ('%s è già in lista per una notifica alle %s.' % (_name, _when))
		elif d == 'rem':
			self.delete_from_notf (self.liststore.get_value (i, 0), self.liststore.get_value (i, 1), self.liststore.get_value (i, 2), self.liststore.get_value (i, 3))
			self.liststore.remove (i)
		
	def check_change (self, d, w=None):
		if self.mnuCheck.active:
			self.timeout_active = True
			timeout_add (600, self.check_for_notf) #check every minutes (60000)
	
	def check_for_notf (self):
		if self.timeout_active == False:
			return False
		l = lt ()
		for p in self.core.progz:
			#try:
			#pt = p[2].split (':')[0] + ':' + str ((int (p[2].split (':')[1])-1)) #program time
			pt = lt ()
			if pt == l:
				self.do_notif (p)
			#except:
			#	pt = p[2]
			#print pt
	
	def do_notif (self, prog):
		self.pynotif ("Sta per iniziare il programma <b>%s</b> sul canale <b>%s</b> ( <b>%s</b> )" % (prog[1], prog[4], prog[2]))
		self.delete_from_notf (prog[0], prog[1], prog[3], prog[2])
		self.liststore.remove (prog[0])
	
	def openweb (self, w):
		prf = 'televisione'
		if self.to_show == 2:
			prf = 'raidue'
		elif self.to_show == 3:
			prf = 'raitre'
		elif self.to_show == 4:
			prf = 'retequattro'
		elif self.to_show == 5:
			prf = 'canalecinque'
		elif self.to_show == 6:
			prf = 'italiauno'
		self.core.run ('firefox http://www.miniportale.it/miniportale/tvoggi/%s.htm' % (prf))
		
	def __init__ (self, core):
		self.timeout_active = False
		self.core = core
		try:
			self.glade = Builder ()
			self.glade.add_from_file ('src/pywot.gui')
		except:
			print "Critical: Cannot init glade."
			exit (1)
		#menus
		self.mnuReload = self.w ('mnuReload')
		self.mnuReload.connect ("activate", self.menu_reload)
		self.mnuQuit = self.w ('mnuQuit')
		self.mnuQuit.connect ("activate", main_quit)
		self.mnuPref = self.w ('mnuPref')
		self.mnuPref.connect ("activate", self.show_config)
		self.mnuRaiUno = self.w ('mnuRai1')
		self.mnuRaiUno.connect ("activate", self.menu_show, "1")
		self.mnuRaiDue = self.w ('mnuRai2')
		self.mnuRaiDue.connect ("activate", self.menu_show, "2")
		self.mnuRaiTre = self.w ('mnuRai3')
		self.mnuRaiTre.connect ("activate", self.menu_show, "3")
		self.mnuRete4 = self.w ('mnuRete4')
		self.mnuRete4.connect ("activate", self.menu_show, "4")
		self.mnuCanale5 = self.w ('mnuCanale5')
		self.mnuCanale5.connect ("activate", self.menu_show, "5")
		self.mnuItalia1 = self.w ('mnuItalia1')
		self.mnuItalia1.connect ("activate", self.menu_show, "6")
		self.mnuMine = self.w ('mnuMine')
		self.mnuMine.connect ("activate", self.menu_show, "7")
		#self.mnuDS = self.w ('mnuDelSelz')
		#self.mnuDS.connect ("activate", self.notf, 'rem')
		self.mnuAbout = self.w ('mnuAbout')
		self.mnuAbout.connect ("activate", self.menu_about)
		self.mnuCheck = self.w ('mnuCheck')
		self.mnuCheck.connect ("toggled", self.check_change)
		#btns
		self.btnNext = self.w ('btnNext')
		self.btnNext.connect ('clicked', self.chann, 'next')
		self.btnForw = self.w ('btnForw') 
		self.btnForw.connect ('clicked', self.chann, 'forw')
		self.btnOpen = self.w ('btnOpen')
		self.btnOpen.connect ('clicked', self.openweb)
		self.btnOpt = self.w ('btnOpt')
		self.btnOpt.connect ('clicked', self.show_config)
		self.btnAdd = self.w ('btnAdd')
		self.btnAdd.connect ('clicked', self.notf, 'add')
		self.btnRemove = self.w ('btnRemove')
		self.btnRemove.connect ('clicked', self.notf, 'rem')
		#status bar
		self.stat = self.w ('stat')
		#treeview
		self.treeview = self.w ('treeview')
		#self.treeview.connect ('cursor-changed', self.listClick)
		self.treeview.connect ('row-activated', self.listDblClick)
		self.liststore = ListStore (str, str, str, str, str)
		self.treeview.set_model (self.liststore)
		self.treeview.set_rules_hint (True)
		txtrend = CellRendererText ()
		col = TreeViewColumn ("#", txtrend, text=0)
		txtrend.set_property ('size', 8500)
		self.treeview.append_column (col)
		txtrend = CellRendererText ()
		col = TreeViewColumn ("Programma", txtrend, text=1)
		txtrend.set_property ('size', 8500)
		col.set_sort_column_id (1)
		self.treeview.append_column (col)
		col = TreeViewColumn ("Orario", txtrend, text=2)
		col.set_sort_column_id (2)
		self.treeview.append_column (col)
		col = TreeViewColumn ("Tipo", txtrend, text=3)
		col.set_sort_column_id (3)
		self.treeview.append_column (col)
		col = TreeViewColumn ("Canale", txtrend, text=4)
		col.set_sort_column_id (4)
		self.treeview.append_column (col)
		self.lblCh = self.w ('lblCh')
		#statusicon
		self.sicon = StatusIcon ()
		self.sicon.set_from_file ('img/tv.png')
		self.sicon.set_visible (True)
		self.sicon.set_tooltip_text ('pywot')
		self.sicon.connect ('activate', self.tray)
		#notificanti
		init ("pywot")
		self.notific = Notification ('pywot', 'Benvenuto in pywot!', self.core.img_path () + 'tv.png')
		self.notific.show ()
		#windows
		self.winAbout = self.w ('winAbout')
		self.winAbout.connect ('response', self.dlgsh, False)
		self.winMain = self.w ('winMain')					
		self.winMain.connect ('destroy', main_quit)
		self.winMain.show ()
		self.sts ('pywot is ready.')
		self.to_show = 1
		self.window_visible = True
		self.menu_reload (None, None)
		main ()
	
	def pynotif (self, m):
		self.notific.update ('pywot', m, self.core.img_path () + 'tv.png')
		self.notific.show ()
		
	def tray (self, w, d=None):
		if self.window_visible == True:
			self.window_visible = False
			self.winMain.hide ()
		else:
			self.window_visible = True
			self.winMain.show ()
								
	def w (self, n):
		try:
			return self.glade.get_object (n)
		except:
			print "Warning: Invalid return for glade.get_object ('%s')" % (n)
